package me.exchange.com.modules.system.service.impl;

import me.exchange.com.exception.EntityExistException;
import me.exchange.com.modules.system.domain.Menu;
import me.exchange.com.modules.system.domain.Role;
import me.exchange.com.modules.system.domain.User;
import me.exchange.com.modules.system.dto.RoleDto;
import me.exchange.com.modules.system.dto.RoleQueryCriteria;
import me.exchange.com.modules.system.dto.RoleSmallDto;
import me.exchange.com.modules.system.dto.UserDto;
import me.exchange.com.modules.system.mapper.RoleMapper;
import me.exchange.com.modules.system.mapper.RoleSmallMapper;
import me.exchange.com.modules.system.repository.RoleRepository;
import me.exchange.com.modules.system.repository.UserRepository;
import me.exchange.com.modules.system.service.RoleService;
import me.exchange.com.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@Service
@CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleSmallMapper roleSmallMapper;
    @Autowired
    private UserRepository userRepository;

    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return roleMapper.toDto(roleRepository.findAll(pageable).getContent());
    }

    @Override
    @Cacheable
    public List<RoleDto> queryAll(RoleQueryCriteria criteria) {
        Sort sort = criteria.getSort();
        return roleMapper.toDto(roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort));
    }

    @Override
    @Cacheable
    public Object queryAll(RoleQueryCriteria criteria, Pageable pageable) {
        Page<Role> page = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(roleMapper::toDto));
    }

    @Override
    @Cacheable(key = "#p0")
    public RoleDto findById(long id) {
        Role role = roleRepository.findById(id).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(),"Role","id",id);
        return roleMapper.toDto(role);
    }

    @Override
    public RoleDto findByRoleName(String name) {
        return roleMapper.toDto(roleRepository.findByRoleName(name));
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public RoleDto create(Role resources) {
        User user=userRepository.findByUsername(SecurityUtils.getUsername());
        resources.setCAdminId(user.getId());
        resources.setCAdminTime(new Timestamp(System.currentTimeMillis()));
        resources.setIsdel(true);
        return roleMapper.toDto(roleRepository.save(resources));
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Role resources) {
        Role role = roleRepository.findById(resources.getId()).orElseGet(Role::new);
        User user=userRepository.findByUsername(SecurityUtils.getUsername());
        ValidationUtil.isNull(role.getId(),"Role","id",resources.getId());
        Role role1 = roleRepository.findByRoleName(resources.getRoleName());

        if(role1 != null && !role1.getId().equals(role.getId())){
            throw new EntityExistException(Role.class,"RoleName",resources.getRoleName());
        }
        resources =(Role)BeanUtil.merge(resources,role);
        resources.setUAdminId(user.getId());
        resources.setUAdminTime(new Timestamp(System.currentTimeMillis()));
        roleRepository.save(resources);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void updateMenu(Role resources, RoleDto roleDTO) {
        Role role = roleMapper.toEntity(roleDTO);
        role.setMenus(resources.getMenus());
        roleRepository.save(role);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void untiedMenu(Long id) {
        roleRepository.untiedMenu(id);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        Role del_role = null;
        for (Long id : ids) {
            del_role = roleRepository.findById(id).orElseGet(Role::new);
            del_role.setIsdel(false);
            roleRepository.save(del_role);
            //roleRepository.deleteById(id);
        }
    }

   @Override
    @Cacheable(key = "'findByUsers_Id:' + #p0")
    public List<RoleSmallDto> findByUsersId(Long id) {
       User user = userRepository.findById(id).orElseGet(User::new);
       Role rolee = roleRepository.findById(user.getRoleId()).orElseGet(Role::new);
       Set<Role> roles = new HashSet<>();
       roles.add(rolee);
       return roleSmallMapper.toDto(new ArrayList<>(roles));
    }

    @Override
    @Cacheable
    public Integer findByRoleId(Long roleId) {
        RoleDto roleDtos =  findById(roleId);
        return roleDtos.getLevel();
    }

    @Override
    @Cacheable(key = "'loadPermissionByUser:' + #p0.username")
    public Collection<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
        Role rolee = roleRepository.findById(user.getRoleId()).orElseGet(Role::new);
        Set<Role> roles = new HashSet<>();
        roles.add(rolee);
        Set<String> permissions = new HashSet<>();
        permissions.addAll(
                roles.stream().flatMap(role -> role.getMenus().stream())
                        .filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
                        .map(Menu::getPermission).collect(Collectors.toSet())
        );
        return permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public void download(List<RoleDto> roles, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RoleDto role : roles) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("角色名称", role.getRoleName());
            map.put("角色级别", role.getLevel());
            map.put("描述", role.getRemark());
            map.put("创建日期", role.getCAdminTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
